extends Node
class_name PlayerStats

#玩家基本属性
var level:int = 1
var current_exp:int = 0
var exp_to_next = 100
var skills: Array = []  # 存储已学习的技能
var skill_database = preload("res://scripts/skills/database/skill_database.gd")
var skill_data = skill_database.skill_data
var coins: int = 0  # 添加金币属性

# 增加基础属性变量，可以在检查器中调整
@export var base_attack: float = 10.0
@export var base_defense: float = 5.0
@export var base_health: int = 100
@export var sword_wave_duration = 3.0  # 基础持续时间
@export var sword_wave_cooldown_time = 10.0  # 基础冷却时间
@export var quick_slash_duration = 0.3  # 疾风斩持续时间
@export var quick_slash_cooldown_time = 2.0  # 疾风斩冷却时间

#基础属性值 
var attack:float = base_attack
var defense:float = base_defense
var max_health = base_health
var current_health:int = max_health

#升级信号
signal level_up(new_level)
signal level_up_effect(position)  # 新增信号用于触发特效
signal learned_new_skill

func _ready():
	print("PlayerStats初始化，当前等级：", level, "，已学习技能：", skills)
	# 确保基础技能已学习
	if not "basic_swing" in skills:
		skills.append("basic_swing")
		print("自动学习基础技能：basic_swing")

#增加经验值，并自动判断是否达到升级条件
func add_exp(amount:int) -> void:
	current_exp += amount
	while current_exp >= exp_to_next:
		current_exp -= exp_to_next
		_level_up()

#内部函数:处理升级逻辑
func _level_up() -> void:
	level += 1
	#升级时可以按比例增加玩家属性
	attack += 2.0
	defense += 1.5
	max_health += 20
	
	# 先发送特效信号
	emit_signal("level_up_effect", get_parent().global_position)
	
	# 创建回血动画
	var tween = create_tween()
	tween.tween_property(self, "current_health", max_health, 0.5)
	
	exp_to_next = int(exp_to_next*1.5)
	
	print("恭喜升级!当前等级:",level)
	emit_signal("level_up",level)

func learn_skill(skill_id: String) -> bool:
	print("PlayerStats.learn_skill被调用，技能ID: ", skill_id)
	
	# 检查技能是否已学习
	if skill_id in skills:
		print("技能已学习: ", skill_id)
		return false  # 已学习的技能不能重复学习

	# 确保技能ID存在于技能数据中
	if skill_id in skill_data:
		var skill_info = skill_data[skill_id]
		print("找到技能信息: ", skill_info.name, ", 所需等级: ", skill_info.cost, ", 当前等级: ", level)
		
		# 检查等级是否足够
		if level >= skill_info.cost:
			# 添加技能到已学习列表
			skills.append(skill_id)
			print("成功学习技能：", skill_id, ", 当前已学习技能: ", skills)
			
			# 发送信号通知技能树更新
			emit_signal("learned_new_skill")
			return true
		else:
			print("等级不足，无法学习技能：", skill_id, ", 需要等级: ", skill_info.cost, ", 当前等级: ", level)
			return false
	else:
		push_error("无效的技能 ID：", skill_id, ", 技能数据中不存在此ID")
		return false

# 添加has_skill方法，用于检查玩家是否已学习某个技能
func has_skill(skill_id: String) -> bool:
	var result = skill_id in skills
	print("检查技能是否已学习: ", skill_id, ", 结果: ", result, ", 当前已学习技能: ", skills)
	return result

# 添加get_level方法，用于获取玩家当前等级
func get_level() -> int:
	print("PlayerStats.get_level被调用，当前等级: ", level)
	return level

func has_property(property_name: String) -> bool:
	return property_name in self
